import uicls
import uiutil
import uiconst
import uthread
import types
import trinity
import blue

class FrameCore(uicls._BaseDecoCore, uicls._GetDecoMetaclassInst('triui.UIFrame')):
    __guid__ = 'uicls.FrameCore'
    default_name = 'framesprite'
    default_left = 0
    default_top = 0
    default_width = 0
    default_height = 0
    default_color = (1.0, 1.0, 1.0, 1.0)
    default_align = uiconst.TOALL
    default_frameConst = uiconst.FRAME_BORDER1_CORNER0
    default_state = uiconst.UI_DISABLED

    def ApplyAttributes(self, attributes):
        uicls._BaseDecoCore.ApplyAttributes(self, attributes)
        color = attributes.get('color', self.default_color)
        if (color is not None):
            self.SetRGB(*color)
        self.LoadFrame(attributes.get('frameConst', self.default_frameConst))



    def HackSetRect(self):
        while (self.texture.pixelBuffer.width == 0):
            blue.pyos.synchro.Yield()

        self.rectWidth = self.texture.pixelBuffer.width
        self.rectHeight = self.texture.pixelBuffer.height



    def LoadFrame(self, frameConst = None):
        (iconNo, cornerSize, offset,) = (frameConst or uiconst.FRAME_BORDER1_CORNER0)
        if (self.texture is None):
            self.texture = trinity.TriTexture()
        if iconNo.startswith('res:'):
            blue.resMan.SetUrgentResourceLoads(True)
            self.texture.pixels = iconNo
            blue.resMan.SetUrgentResourceLoads(False)
            uthread.new(self.HackSetRect)
            self.SetCornerSize(cornerSize)
            self.SetPadding(offset, offset, offset, offset)
            return 
        uiutil.MapIcon(self, iconNo, ignoreSize=True)
        self.SetCornerSize(cornerSize)
        if (self.GetAlign() == uiconst.TOALL):
            self.left = 0
            self.top = 0
            self.width = 0
            self.height = 0
            self.SetPadding(offset, offset, offset, offset)
        else:
            self.left = (offset + self.left)
            self.top = (offset + self.top)
            self.width = (self.width + (-offset * 2))
            self.height = (self.height + (-offset * 2))



    def SetCornerSize(self, cornerSize):
        self.cornerSize = cornerSize



    def GetCornerSize(self):
        return self.cornerSize



    def SetRGB(self, *color):
        self.color.SetRGB(*color)


    SetRGBA = SetRGB

    def GetRGB(self):
        return (self.color.r,
         self.color.g,
         self.color.b)



    def GetRGBA(self):
        return (self.color.r,
         self.color.g,
         self.color.b,
         self.color.a)



    def SetAlpha(self, alpha):
        self.color.a = alpha



    def GetAlpha(self):
        return self.color.a




class Frame(FrameCore):
    __guid__ = 'uicls.Frame'
    default_color = (1.0, 1.0, 1.0, 0.5)


